<?php

/**
 * DealsController is the default controller for this application
 */
class DealsController extends BrowseControllerBase {
	/**
	 * GrouponDataService object
	 *
	 * @var GrouponDataService object
	 */
	public $grouponDataService = null;
	
	public $nlCheckout = null;
	public $dealsDataService = null;
	/**
	 * GrouponCommentDataService object
	 *
	 * @var GrouponCommentDataService object
	 */
	public $grouponCommentDataService = null;
	
	/**
	 *
	 * DealOrderDataService
	 * @var DealOrderDataService Object
	 */
	public $dealOrderDataService = null;
	
	/**
	 *
	 * OrderAddressDataService
	 * @var OrderAddressDataService Object
	 */
	public $orderAddressDataService = null;
	/**
	 *
	 * UsersDataService Object
	 * @var UsersDataService object
	 */
	public $userDataService = null;
	
	public $currentUserId = null;
	/**
	 * Constructor of index
	 */
	public function __construct() {
		parent::__construct ();
		
		// Set page name
		$this->setPageName ( 'groupon' );
		
		// Initialise GrouponDataService
		$this->grouponDataService = new GrouponDataService ();
		//
		$this->dealsDataService = new DealsDataService ();
		// Initialise GrouponCommentDataService
		//		$this->grouponCommentDataService = new GrouponCommentDataService();
		

		//        //Check if User is logged in
		$this->currentUserId = $this->authentication->getCurrentUserId ();
		//        if ($currentUserId == null) {
		//            // Go on to login page
		//            $url = Zend_Registry::get('config')->APPLICATION_URL . '/Browse/';
		//            CommonUtils::redirect($url);
		//            return -1;
		//        }
		

		// Init all Data Service
		$this->userDataService = new UserDataService ();
		//        // Check if user has verified payment or expired here
		//        $currentUser = $this->userDataService->getById($currentUserId);
		////        if(!empty($currentUser) && $currentUser->userType != "MEMBER") {
		//        if(!empty($currentUser)) {
		//            // Go on to login page
		//            $url = Zend_Registry::get('config')->APPLICATION_URL . '/Browse/';
		//            CommonUtils::redirect($url);
		//            return -1;
		//        }
		

		$this->dealOrderDataService = new DealOrderDataService ();
		$this->orderAddressDataService = new OrderAddressDataService ();
		$this->nlCheckout = new Nganluong ();
	
		// Load Payment Configuration
	//		$this->loadAllPayment ();
	}
	
	/**
	 * The "index" action is the default action for all controllers -- the
	 * landing page of the site.
	 *
	 * @return void
	 *
	 */
	public function indexAction() {
		//can get all deals.....
		if (isset ( $_COOKIE ['city'] )) {
			$city = $_COOKIE ['city'];
		} else {
			$city = 1;
		}
		$arr = array('G.city_id' => $city);
		$where = " AND D.status > 0";
		$where .= " AND DATE_FORMAT(D.started_deal, '%Y-%m-%d %H:%i:%s') <= '".date('Y-m-d') . ' ' . date('H:i:s') ."'";
		$where .= " AND DATE_FORMAT(D.expired_deal, '%Y-%m-%d %H:%i:%s') >= '".date('Y-m-d') . ' ' . date('H:i:s')."'";
		if($this->getQuery('cat', 0) != 0){
			$arr = array_merge($arr, array('G.category_id' => $this->getQuery('cat', 0)));
			$this->smarty->assign('categoryActice', $this->getQuery('cat', 0));
		}
		$listDeals = $this->dealsDataService->getAllDeals ( $arr , 'rand()', null, null, $where );
		$this->smarty->assign ( 'listDeals', $listDeals );
		$this->smarty->assign('this', $this);
		$this->smarty->assign('grouponEntity', new GrouponEntity());
		$this->smarty->assign('pageName', 'index');
		if ($this->isMobileMode == false) {
			$this->smarty->assign ( 'SMARTY_CONTENT_PATH', 'Browse/Deals/index.tpl' );
			$this->smarty->display ( APPLICATION_PATH . '/Layouts/Browse/MainLayoutShowAll.tpl' );
		}else{
			$this->smarty->assign ( 'SMARTY_CONTENT_PATH', 'Mobile/Deals/index.tpl' );
			$this->smarty->display ( APPLICATION_PATH . '/Layouts/Mobile/MainLayout.tpl' );
		}
	}
	
	public function detailsAction() {
		$id = $this->getQuery ( 'id' );
		if ($id == '') {
			$id = $this->getPost ( 'id', '' );
		}
		$id = intval ( $id );
		
		$city = $this->getQuery ( 'city', 1 );
		
		//get Deal
		$dealEntity = $this->dealsDataService->getById ( $id );
		// Get data
		$grouponEntity = $this->grouponDataService->getById ( $dealEntity->groupon_id );
		//get Address of Groupon
		$contactAddressDataService = new ContactAddressDataService ();
		$listAddress = $contactAddressDataService->getByGrouponId ( $grouponEntity->id );
		
		if (empty ( $grouponEntity ) || empty ( $dealEntity )) {
			// Go on to login page
			$url = Zend_Registry::get ( 'config' )->APPLICATION_URL;
			CommonUtils::redirect ( $url );
			return - 1;
		}
		//get list another deal
		$listAnotherDeals = $this->dealsDataService->getAnotherDeals ( $id, $city );
		// Get SettingsDataService
		$settingsDataService = new SettingsDataService ();
		$perDiscount = round ( ($dealEntity->original_price - $dealEntity->sale_price) / $dealEntity->original_price * 100 );
		//get Lasted Comment
		$commentDataService = new DealCommentDataService();
		$listComment = $commentDataService->getItems(array('deal_id', $id), 'comment_id desc', 0,1);
		$this->smarty->assign ( 'totalComment', $commentDataService->getTotals(array('deal_id'=>$id)) );
		$isExpired = (strtotime($dealEntity->expired_deal) <= strtotime(date('Y-m-d H:i:s')));

		$this->smarty->assign ( 'lastedComment', $listComment[0] );
		$this->smarty->assign('userComment', $this->userDataService->getById($listComment[0]->user_id));
		$this->smarty->assign ( 'listAnotherDeals', $listAnotherDeals );
		$this->smarty->assign ( 'perDiscount', $perDiscount );
		$this->smarty->assign ( 'grouponEntity', $grouponEntity );
		$this->smarty->assign ( 'dealsEntity', $dealEntity );
		$this->smarty->assign ( 'listAddress', $listAddress );
		$this->smarty->assign ( 'googleApiCode', $settingsDataService->getValue ( GOOGLE_API_CODE ) );
		$this->smarty->assign ( 'duration', strtotime ( $dealEntity->expired_deal ) - time () );
		$this->smarty->assign('isExpired', $isExpired);
		$this->smarty->assign ( 'this', $this);
		if ($this->isMobileMode == false) {
			$this->smarty->assign ( 'SMARTY_CONTENT_PATH', 'Browse/Deals/details.tpl' );
			$this->smarty->display ( APPLICATION_PATH . '/Layouts/Browse/MainLayoutDetailAll.tpl' );
		}else{
			$this->smarty->assign ( 'SMARTY_CONTENT_PATH', 'Mobile/Deals/details.tpl' );
			$this->smarty->display ( APPLICATION_PATH . '/Layouts/Mobile/MainLayout.tpl' );
		}
	}
	public function BuyDealAction() {
		$id = $this->getQuery ( 'id' );
		if ($id == '') {
			$id = $this->getPost ( 'id', '' );
		}
		$id = intval ( $id );
		//city
		$city = $this->getQuery ( 'city' );
		if ($city == '') {
			$city = $this->getPost ( 'city', 1 );
		}
		//if not login, redierect to register or signin
		if (($this->currentUserId == null) || ($this->currentUserId != null && $this->authentication->getUserType () != ROLE_MEMBER)) {
			// Go on to login page
			$url = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/Browse/Deals/RegisterBuy/city/' . $city . '/id/' . $id;
			CommonUtils::redirect ( $url );
			return - 1;
		}
		
		//get Deal
		$dealEntity = $this->dealsDataService->getById ( $id );
		// Get data
		$grouponEntity = $this->grouponDataService->getById ( $dealEntity->groupon_id );
		//get User
		$userDataService = new UserDataService ();
		$userEntity = $userDataService->getById ( $this->currentUserId );
		//get user Location 
		$userLocationDataService = new UserLocationDataService ();
		$userLocationEntity = $userLocationDataService->getBuyUserAndCity ( $this->currentUserId, $city, true );
		$this->smarty->assign ( 'grouponEntity', $grouponEntity );
		$this->smarty->assign ( 'dealsEntity', $dealEntity );
		$this->smarty->assign ( 'userEntity', $userEntity );
		$this->smarty->assign ( 'userLocationEntity', $userLocationEntity );
		$this->smarty->assign ( 'city_id', $city );
		
		$this->smarty->assign ( 'SMARTY_CONTENT_PATH', 'Browse/Deals/buydeal.tpl' );
		$this->smarty->display ( APPLICATION_PATH . '/Layouts/Browse/MainLayout.tpl' );
	}
	public function RegisterBuyAction() {
		
		$id = $this->getQuery ( 'id' );
		if ($id == '') {
			$id = $this->getPost ( 'id', '' );
		}
		$id = intval ( $id );
		//city
		$city = $this->getQuery ( 'city' );
		if ($city == '') {
			$city = $this->getPost ( 'city', 1 );
		}
		
		$result = SUCC;
		$message = 'Signup Fails. Please try again!';
		if ($this->getPost ( 'resgister' )) {
			$email = $this->getPost ( 'email', '' );
			$password = $this->getPost ( 'password', '' );
			$confirmPassword = $this->getPost ( 'confirmPassword', '' );
			$fullname = $this->getPost ( 'fullname', '' );
			if ($password != $confirmPassword) {
				$result = ERROR;
				$message = 'Password mismatch! Please try again!';
				$this->smarty->assign ( 'message', $message );
			}
			$userDataService = new UserDataService ();
			if ($userDataService->checkExistEmail ( $email ) == SUCC) {
				$result = ERROR;
				$message .= '$email is exist in system !';
			
			}
			if ($result != ERROR) {
				$authenticate = new Authentication ();
				$userEntity = $userDataService->beforeCreate ();
				$userEntity->email = $email;
				$userEntity->fullname = $fullname;
				$userEntity->password = $authenticate->encryptPassword ( $password );
				$userEntity->status = UserEntity::ACTIVE;
				$userEntity->userType = ROLE_MEMBER;
				$userEntity->balance = 0;
				$userId = $userDataService->create ( $userEntity );
				// Try to login this user
				$result = $userDataService->login ( $email, $password );
				if ($result != SUCC) {
					$message = "Ä�Äƒng nháº­p tháº¥t báº¡i!";
				} else {
					$result = SUCC;
					$message = "Táº¡o user thĂ nh cĂ´ng";
					$url = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/Browse/Deals/BuyDeal/city/' . $city . '/id/' . $id;
					CommonUtils::redirect ( $url );
					return - 1;
				}
			}
		}
		//if login, redierect to buydeal
		if ($this->currentUserId != null && $this->authentication->getUserType () == ROLE_MEMBER) {
			// Go on to buydeal
			$url = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/Browse/Deals/BuyDeal/city/' . $city . '/id/' . $id;
			CommonUtils::redirect ( $url );
			return - 1;
		}
		//get Deal
		$dealEntity = $this->dealsDataService->getById ( $id );
		// Get data
		$grouponEntity = $this->grouponDataService->getById ( $dealEntity->groupon_id );
		
		$this->smarty->assign ( 'grouponEntity', $grouponEntity );
		$this->smarty->assign ( 'dealsEntity', $dealEntity );
		$this->smarty->assign ( 'city', $city );
		
		if ($this->isMobileMode == false) {
			$this->smarty->assign ( 'SMARTY_CONTENT_PATH', 'Browse/Deals/registerbuy.tpl' );
			$this->smarty->display ( APPLICATION_PATH . '/Layouts/Browse/MainLayout.tpl' );
		}else{
			$this->smarty->assign ( 'SMARTY_CONTENT_PATH', 'Mobile/Deals/registerbuy.tpl' );
			$this->smarty->display ( APPLICATION_PATH . '/Layouts/Mobile/MainLayout.tpl' );
		}
	}
	
	public function LoginBuyAction() {
		
		$id = $this->getQuery ( 'id' );
		if ($id == '') {
			$id = $this->getPost ( 'id', '' );
		}
		$id = intval ( $id );
		//city
		$city = $this->getQuery ( 'city' );
		if ($city == '') {
			$city = $this->getPost ( 'city', 0 );
		}
		if ($return_url = $this->getQuery ( 'return_url' )) {
			$this->smarty->assign ( 'return_url', $return_url );
		}
		if ($this->getPost ( 'login' )) {
			
			$email = $this->getPost ( 'email', '' );
			$password = $this->getPost ( 'password', '' );
			// Try to login this user
			$userDataService = new UserDataService ();
			$result = $userDataService->login ( $email, $password );
			if ($result != SUCC) {
				$message = "Có lỗi xảy ra!";
			} else {
				if ($return_url = $this->getPost ( 'return_url' )) {
					$return_url = str_replace ( 'EquaL', '=', $return_url );
					$return_url = str_replace ( 'AnD', '&', $return_url );
					$return_url = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/index.php?' . $return_url;
					
					CommonUtils::redirect ( $return_url );
				}
				$url = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/Browse/Deals/BuyDeal/city/' . $city . '/id/' . $id;
				CommonUtils::redirect ( $url );
				return - 1;
			}
		}
		
		//if not login, redierect to register or signin
		if ($this->currentUserId != null && $this->authentication->getUserType () == ROLE_MEMBER) {
			// Go on to login page
			$url = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/Browse/Deals/BuyDeal/city/' . $city . '/id/' . $id;
			CommonUtils::redirect ( $url );
			return - 1;
		}
		//get Deal
		$dealEntity = $this->dealsDataService->getById ( $id );
		// Get data
		$grouponEntity = $this->grouponDataService->getById ( $dealEntity->groupon_id );
		
		$this->smarty->assign ( 'grouponEntity', $grouponEntity );
		$this->smarty->assign ( 'dealsEntity', $dealEntity );
		$this->smarty->assign ( 'city', $city );
		
		$this->smarty->assign ( 'SMARTY_CONTENT_PATH', 'Browse/Deals/loginbuy.tpl' );
		$this->smarty->display ( APPLICATION_PATH . '/Layouts/Browse/MainLayout.tpl' );
	}
	
	/**
	 * Process Payment for Signup
	 */
	public function processpaymentAction() {
		$feeSettingsEntity = $this->settingsDataService->getItem ( FEE_SERVICE );
		$curencySettingsEntity = $this->settingsDataService->getItem ( CURRENCY_USD_VND );
		$userId = $this->authentication->getCurrentUserId ();
		$quantity = $this->getPost ( 'quantity', '' );
		$dealId = $this->getQuery ( 'id' );
		if ($dealId == '') {
			$dealId = $this->getPost ( 'id', '' );
		}
		//get info of user order
		$recipient_name = $this->getPost ( 'fullname', '' );
		$recipient_phone = $this->getPost ( 'phone', '' );
		$recipient_number = $this->getPost ( 'number_house', '' );
		$recipient_street = $this->getPost ( 'street', '' );
		$recipient_ward_ngo = $this->getPost ( 'ward_ngo', '' );
		$recipient_district = $this->getPost ( 'district', 0 );
		$note = $this->getPost ( 'note', '' );
		$isGift = $this->getPost ( 'isGift', 0 );
		//get infor sender
		if ($isGift) {
			$sender_name = $this->getPost ( 'sender_fullname', '' );
			$sender_phone = $this->getPost ( 'sender_phone', '' );
			$sender_number = $this->getPost ( 'sender_number_house', '' );
			$sender_street = $this->getPost ( 'sender_street', '' );
			$sender_ward_ngo = $this->getPost ( 'sender_ward_ngo', '' );
			$sender_district = $this->getPost ( 'sender_district', 0 );
		}
		//check
		$dealEntity = $this->dealsDataService->getById ( $dealId );
		$grouponEntity = $this->grouponDataService->getById ( $dealEntity->groupon_id );
		if (empty ( $dealEntity )) {
			// Go on to login page
			$url = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/Browse/';
			CommonUtils::redirect ( $url );
			return - 1;
		}
		//check deal active
		if((strtotime($dealEntity->expired_deal) <= strtotime(date('Y-m-d H:i:s')))
		|| ($dealEntity->bought_count >= $dealEntity->max_bought)
		){
			$url = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/Browse/';
			CommonUtils::redirect ( $url );
			return - 1;
		} 
		$amount = $dealEntity->sale_price * $quantity;
		$paymentMethod = $this->getPost ( 'paymentMethod', '' );
		$actionForm = $this->getPost ( 'actionForm', '' );
		if (! empty ( $amount ) && floatval ( $amount ) > 0 && $actionForm != "cancel") {
			// Save to order table
			$dealOrderEntity = $this->dealOrderDataService->beforeCreate ();
			$dealOrderEntity->user_id = $userId;
			
			$dealOrderEntity->deal_id = $dealEntity->id;
			$dealOrderEntity->order_date = date ( 'Y-m-d H:i:s' );
			$dealOrderEntity->bar_code = '';
			$dealOrderEntity->quantity = $quantity;
			$dealOrderEntity->total_price = $amount;
			$dealOrderEntity->service_fee = $amount * $feeSettingsEntity->value / 100;
			$dealOrderEntity->merchant_money = $amount - $amount * $feeSettingsEntity->value / 100;
			$dealOrderEntity->payment_status = '';
			$dealOrderEntity->order_status = DealOrderEntity::NOTCONFIRM;
			$dealOrderEntity->payment_method = '';
			$dealOrderEntity->merchant_money = $amount - $amount * $feeSettingsEntity->value / 100;
			$dealOrderEntity->type = ($isGift) ? 'gift' : '';
			$id = $this->dealOrderDataService->create ( $dealOrderEntity );
			
			if (empty ( $id )) {
				$this->indexAction ();
				return;
			}
			$dealOrderEntity = $this->dealOrderDataService->getById ( $id );
			
			//save to user_address table
			$orderAddressEntity = $this->orderAddressDataService->beforeCreate ();
			$orderAddressEntity->deal_order_id = $id;
			$orderAddressEntity->recipient_name = $recipient_name;
			$orderAddressEntity->recipient_phone = $recipient_phone;
			$orderAddressEntity->recipient_number = $recipient_number;
			$orderAddressEntity->recipient_street = $recipient_street;
			$orderAddressEntity->recipient_ward_ngo = $recipient_ward_ngo;
			$orderAddressEntity->recipient_district = $recipient_district;

			$deal_order_id = $this->orderAddressDataService->create ( $orderAddressEntity );
			$orderAddressEntity = $this->orderAddressDataService->getById ( $id );
			if ($isGift) {
				$orderAddressEntity->sender_name = $sender_name;
				$orderAddressEntity->sender_phone = $sender_phone;
				$orderAddressEntity->sender_number = $sender_number;
				$orderAddressEntity->sender_street = $sender_street;
				$orderAddressEntity->sender_ward_ngo = $sender_ward_ngo;
				$orderAddressEntity->sender_district = $sender_district;
				$this->orderAddressDataService->update ( $orderAddressEntity );

			}
			if ($paymentMethod == PAYMENT_PAYPAL) {
				//Check if exist previous Deal, then cancel it before create a new one
				// Check if this user is verified.
				//				$arrElement = array ();
				//				$arrElement ['user_id'] = $this->authentication->getCurrentUserId ();
				//				$arrElement ['payment_method'] = PAYMENT_PAYPAL;
				//				$arrElement ['payment_status'] = DealOrderEntity::COMPLETED;
				//				$items = $this->dealOrderDataService->getItems ( $arrElement, " order_date DESC " );
				//				if (count ( $items ) > 0) {
				//					$item = $items [0];
				//					// Get ProfileId
				//					$profileId = $item->user_id;
				//					try {
				//						$paypalConfig = $this->settingsDataService->getPaypalSettings ();
				//						$paypalGateway = new PayPalGateway ( $paypalConfig );
				//						$paypalGateway->setConfig ( $paypalConfig );
				//						
				//						$paypalGateway->cancelSubscription ( $profileId, "User Cancel the recurring payment" );
				//						
				//						$item->user_id = "";
				//						$item->payment_status = DealOrderEntity::CANCELLED;
				//						$this->dealOrderDataService->update ( $item );
				//					} catch ( Exception $ex ) {
				//						//echo $ex->getMessage();
				//					//die();
				//					}
				//				
				//				}
				

				//update order
				$dealOrderEntity->payment_status = DealOrderEntity::PENDING;
				$dealOrderEntity->payment_method = PAYMENT_PAYPAL;
				$this->dealOrderDataService->update ( $dealOrderEntity );
				try {
					$params ['return_url'] = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/index.php?authen=Browse&control=Deals&action=returnPayment' . '&state=return&order_id=' . $id;
					$params ['cancel_url'] = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/index.php?authen=Browse&control=Deals&action=returnPayment' . '&state=cancel&order_id=' . $id;
					$params ['ipn_url'] = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/index.php?authen=Browse&control=PaypalIpn&action=index&order_id=' . $id;
					
					$params ['vendor_order_id'] = md5 ( $id . $grouponEntity->title );
					$params ['price'] = $amount;
					$params ['description'] = 'sale';
					$params ['amount'] = intval ( $quantity );
					
					$paypalConfig = $this->settingsDataService->getPaypalSettings ();
					$paypalGateway = new PayPalGateway ( $paypalConfig );
					$paypalGateway->setConfig ( $paypalConfig );
					// Get GateWay URL
					$transactionUrl = $paypalGateway->getGatewayUrl ();
					$transaction = $paypalGateway->createBuyNowTransaction ( $grouponEntity, $dealEntity, $params );
					
					$transactionData = $transaction->getData ();
					// Handle redirection
					$transactionUrl .= '?cmd=_express-checkout&token=' . $transactionData ['token'];
					
					$dealOrderEntity = $this->dealOrderDataService->beforeUpdate ( $id );
					$dealOrderEntity->token = urldecode ( $transactionData ['token'] );
					$dealOrderEntity->payment_status = DealOrderEntity::PROCESSING;
					$this->dealOrderDataService->update ( $dealOrderEntity );
					
					header ( "Location: " . $transactionUrl );
				} catch ( ExceptionAbstract $ex ) {
				}
			} else if ($paymentMethod == PAYMENT_2CHECKOUT) {
				
				// Check if there's product
				// Save to deposit table
				$dealOrderEntity = $this->dealOrderDataService->beforeCreate ();
				$dealOrderEntity->cost = round ( $amount, 2 );
				$dealOrderEntity->userId = $userId;
				if ($brandFree == "1") {
					$dealOrderEntity->brandFee = 5;
					$amount = round ( $amount, 2 ) + 5;
					$dealOrderEntity->totalFee = $amount;
				} else {
					$dealOrderEntity->brandFee = 0;
				}
				
				// Assign PaymentMethod
				$dealOrderEntity->paymentMethod = PAYMENT_2CHECKOUT;
				$dealOrderEntity->note = 'Payment:' . date ( 'Y-m-d H:i:s' );
				$dealOrderEntity->currency = 'GBP';
				$dealOrderEntity->dealOptionId = $dealOptionId;
				$dealOrderEntity->createdDate = date ( 'Y-m-d H:i:s' );
				$today = date ( 'Y-m-d' );
				$expiredDate = date ( 'Y-m-d', strtotime ( "$today + 1 months" ) );
				$dealOrderEntity->expiredDate = $expiredDate;
				$dealOrderEntity->payment_status = DealOrderEntity::PENDING;
				$id = $this->dealOrderDataService->create ( $dealOrderEntity );
				
				if (empty ( $id )) {
					$this->indexAction ();
					return;
				}
				try {
					$params ['return_url'] = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/index.php?authen=Browse&control=Payment&action=returnPayment2' . '&state=return&order_id=' . $id;
					$params ['cancel_url'] = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/index.php?authen=Browse&control=Payment&action=returnPayment2' . '&state=cancel&order_id=' . $id;
					$params ['merchant_order_id'] = $id;
					
					$checkoutConfig = $this->settingsDataService->get2CheckoutSettings ();
					unset ( $checkoutConfig ['vendor_id'] );
					$checkoutGateway = new TwoCheckoutGateway ( $checkoutConfig );
					$checkoutGateway->setConfig ( $checkoutConfig );
					// Get GateWay URL
					$transactionUrl = $checkoutGateway->getGatewayUrl ();
					$transaction = $checkoutGateway->createSubscriptionTransaction ( $dealOrderEntity, $params );
					
					$transactionData = $transaction->getData ();
					$transactionUrl = $checkoutGateway->getGatewayUrl ();
					$transactionMethod = $checkoutGateway->getGatewayMethod ();
					
					$dealOrderEntity = $this->dealOrderDataService->beforeUpdate ( $id );
					$dealOrderEntity->token = NULL;
					$dealOrderEntity->payment_status = DealOrderEntity::PROCESSING;
					$this->dealOrderDataService->update ( $dealOrderEntity );
					$transactionUrl .= '?' . http_build_query ( $transactionData );
					header ( "Location: " . $transactionUrl );
				} catch ( ExceptionAbstract $ex ) {
					// We will add Log here
					echo $ex->getMessage ();
				
				}
			} else if ($paymentMethod == PAYMENT_NGANLUONG) {
				//update order
				$dealOrderEntity->payment_status = DealOrderEntity::PENDING;
				$dealOrderEntity->payment_method = PAYMENT_NGANLUONG;
				$this->dealOrderDataService->update ( $dealOrderEntity );
				
				//redirect to site nganluong
				$return_url = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/index.php?authen=Browse&control=Deals&action=returnnl';
				$receiver = 'thanhphi89@gmail.com';
				$transaction_info = 'Mua hội - ' . $grouponEntity->groupon_name;
				$order_code = $id;
				$price = $dealEntity->sale_price;
				$urlNganluong = $this->nlCheckout->buildCheckoutUrl ( $return_url, $receiver, $transaction_info, $order_code, $price );
				header ( "Location: " . $urlNganluong );
			} else if ($paymentMethod == PAYMENT_BALANCE) {
				//check money of account with money pay
				$userDataService = new UserDataService ();
				$userEntity = $userDataService->getById ( $userId );
				if ($userEntity->balance < $amount) {
					$url = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/Browse/Deals/cancel';
					CommonUtils::redirect ( $url );
					return;
				}
				$userEntity->balance = $userEntity->balance - $amount;
				$userDataService->update ( $userEntity );
				
				//update order
				$dealOrderEntity->payment_status = DealOrderEntity::COMPLETED;
				$dealOrderEntity->payment_method = PAYMENT_BALANCE;
				$this->dealOrderDataService->update ( $dealOrderEntity );
				
				//update bought_count of deal
				$dealEntity->bought_count = $dealEntity->bought_count + $quantity;
				$this->dealsDataService->update ( $dealEntity );
				
				$dealEntity = $this->dealsDataService->getById ( $dealEntity->id );
				// update status of deal
				$dealEntity->updateStatus ();
				//if tipped
				if ($dealEntity->bought_count >= $dealEntity->min_bought) {
					if ($dealEntity->tipped_date == '0000-00-00 00:00:00') {
						$dealEntity->tipped_date = new Zend_Db_Expr ( 'NOW()' );
						$dealEntity = $this->dealsDataService->getById ( $dealOrderEntity->deal_id );
					}
				
		// Update code for Buyer
				// $dealEntity->updateCodeForBuyer();
				}
				
				$url = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/Browse/Deals/completed';
				CommonUtils::redirect ( $url );
				return;
			} else if ($paymentMethod == PAYMENT_INVOICE) {
				//update order
				$dealOrderEntity->payment_status = DealOrderEntity::PENDING;
				$dealOrderEntity->payment_method = PAYMENT_INVOICE;
				$this->dealOrderDataService->update ( $dealOrderEntity );
				
				$url = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/Browse/Deals/completed';
				CommonUtils::redirect ( $url );
				return;
			}
		} else if ($actionForm == "cancel") {
		
		}
	}
	/**
	 * Handle Return Pay from Paypal
	 */
	public function returnPaymentAction() {
		$paypalConfig = $this->settingsDataService->getPaypalSettings ();
		$paypalGateway = new PayPalGateway ( $paypalConfig );
		$paypalGateway->setConfig ( $paypalConfig );
		$token = $_GET ['token'];
		$dealOrderEntity = $this->dealOrderDataService->getByToken ( $token );
		$dealEntity = $this->dealsDataService->getById ( $dealOrderEntity->deal_id );
		//        $grouponEntity = $this->grouponDataService->getById($dealEntity->groupon_id);
		if (is_null ( $dealOrderEntity )) {
			$this->indexAction ();
			return;
		}
		try {
			$result = $paypalGateway->onTransactionReturn ( $dealOrderEntity, $_GET, 'USD' );
			//            $paypalGateway->refundForBuyer($dealEntity, $grouponEntity, $dealOrderEntity);
			if ($result == SUCC) {
				$dealOrderEntity->payment_status = DealOrderEntity::COMPLETED;
				$this->dealOrderDataService->update ( $dealOrderEntity );
				
				// tang so luong mua hang
				$dealEntity->bought_count = $dealEntity->bought_count + $dealOrderEntity->quantity;
				$this->dealsDataService->update ( $dealEntity );
				
				$dealEntity = $this->dealsDataService->getById ( $dealEntity->id );
				// update status of deal
				$dealEntity->updateStatus ();
				//if tipped
				if ($dealEntity->bought_count >= $dealEntity->min_bought) {
					if ($dealEntity->tipped_date == '0000-00-00 00:00:00') {
						$dealEntity->tipped_date = new Zend_Db_Expr ( 'NOW()' );
						$dealEntity = $this->dealsDataService->getById ( $dealOrderEntity->deal_id );
					}
				
		// Update code for Buyer
				// $dealEntity->updateCodeForBuyer();
				}
				
				$url = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/Browse/Deals/completed/id/' . $dealEntity->id;
				CommonUtils::redirect ( $url );
				return;
			} else {
				
				$url = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/Browse/Deals/cancel/id' . $dealEntity->id;
				CommonUtils::redirect ( $url );
				return;
			}
		} catch ( ExceptionAbstract $ex ) {
			$url = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/Browse/Deals/cancel/id' . $dealEntity->id;
			CommonUtils::redirect ( $url );
			return;
		
		//echo $ex->getMessage();
		}
	
	}
	/**
	 * Handle when Paypal callback
	 */
	public function paymentcompleteAction() {
		$nvpComponent = new PaypalNvpComponent ();
		$token = $_GET ['token'];
		// GetExpressCheckoutDetails to get PAYERID
		$result = $nvpComponent->getExpressCheckoutDetails ( array ('token' => $token ) );
		
		$dealOrderEntity = $this->dealOrderDataService->getByToken ( $token );
		
		if (is_null ( $dealOrderEntity )) {
			$this->indexAction ();
			return;
		}
		
		// Redirect to complete page
		$url = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/Browse/Deals/completed';
		CommonUtils::redirect ( $url );
		return;
	}
	
	public function completedAction() {
		$this->smarty->assign ( 'SMARTY_CONTENT_PATH', 'Browse/Deals/payment_complete.tpl' );
		$this->smarty->display ( APPLICATION_PATH . '/Layouts/Browse/MainLayout.tpl' );
	}
	
	/**
	 * Cancel Payment Handling
	 */
	public function cancelAction() {
		$this->smarty->assign ( 'SMARTY_CONTENT_PATH', 'Browse/Deals/payment_cancel.tpl' );
		$this->smarty->display ( APPLICATION_PATH . '/Layouts/Browse/MainLayout.tpl' );
	}
	
	/**
	 * 
	 * Handle return Pay from Nganluong
	 */
	public function returnnlAction() {
		
		$transaction_info = @$_GET ['transaction_info'];
		$order_code = @$_GET ['order_code'];
		$price = @$_GET ['price'];
		$payment_id = @$_GET ['payment_id'];
		$payment_type = @$_GET ['payment_type'];
		$error_text = @$_GET ['error_text'];
		$secure_code = @$_GET ['secure_code'];
		//get Deal Order
		$dealOrderEntity = $this->dealOrderDataService->getById ( $order_code );
		//get Deal Object
		$dealEntity = $this->dealsDataService->getById ( $dealOrderEntity->deal_id );
		if (empty ( $dealEntity ) || empty ( $dealOrderEntity )) {
			// Go on to login page
			$url = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/Browse/Deals/cancel';
			CommonUtils::redirect ( $url );
			return - 1;
		}
		$check = $this->nlCheckout->verifyPaymentUrl ( $transaction_info, $order_code, $price, $payment_id, $payment_type, $error_text, $secure_code );
		if ($check) {
			//thay doi status order
			$dealOrderEntity->payment_status = DealOrderEntity::COMPLETED;
			$this->dealOrderDataService->update ( $dealOrderEntity );
			// tang so luong mua hang
			$dealEntity->bought_count = $dealEntity->bought_count + $dealOrderEntity->quantity;
			$this->dealsDataService->update ( $dealEntity );
			//kiem tra neu >= so luong dat toi thieu, update ngày tipped
			$dealEntity = $this->dealsDataService->getById ( $dealEntity->id );
			// update status of deal
			$dealEntity->updateStatus ();
			//if tipped
			if ($dealEntity->bought_count >= $dealEntity->min_bought) {
				if ($dealEntity->tipped_date == '0000-00-00 00:00:00') {
					$dealEntity->tipped_date = new Zend_Db_Expr ( 'NOW()' );
					$dealEntity = $this->dealsDataService->getById ( $dealOrderEntity->deal_id );
				}
			
		// Update code for Buyer
			// $dealEntity->updateCodeForBuyer();
			}
			
			//chuyen toi trang mua thanh cong
			$url = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/Browse/Deals/completed';
			CommonUtils::redirect ( $url );
			return - 1;
		} else {
			//co loi xay ra, khach hang kiem tra lai, chuyen ve trang bao loi
			$url = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/Browse/Deals/cancel';
			CommonUtils::redirect ( $url );
			return - 1;
		}
	}
	public function refundForBuyer($deal, $groupon, $buyer) {
		
		//Prepare data for payment
		$params = array ();
		$params ['EMAILSUBJECT'] = "Refund for buyer ID: $buyer->id of groupon title [{$groupon->title}] completed";
		$params ['RECEIVERTYPE'] = "EmailAddress";
		$params ['CURRENCYCODE'] = 'USD';
		//$params['L_EMAIL0'] = $account->paypal_email;
		//total money must pay to owner
		

		$params ['L_Amt0'] = $buyer->total_price;
		$params ['L_NOTE0'] = "Refund for buyer ID:$buyer->id of groupon title [{$groupon->title}] completed";
		try {
			$paypalConfig = $this->settingsDataService->getPaypalSettings ();
			$paypalGateway = new PayPalGateway ( $paypalConfig );
			$paypalGateway->setConfig ( $paypalConfig );
			$response = $paypalGateway->getService ()->refundTransaction ( $buyer->gateway_transaction_id, null, 'Full', $buyer->total_price, $params ['CURRENCYCODE'], 'refund' );
			return true;
			
			$plugin->getGateway ()->getLog ()->log ( 'Refund Successful: ' . print_r ( $response, true ), Zend_Log::INFO );
		} catch ( Engine_Service_PayPal_Exception $e ) {
			// Let's log it
			$plugin->getGateway ()->getLog ()->log ( 'Refund Got Exception: ' . print_r ( $e->getMessage (), true ), Zend_Log::ERR );
			return false;
		}
	}
	
	public function  calculatorDuration($expired_deal){
		return strtotime ($expired_deal) - time ();		
	}
	public function explodePicture($sPicture){
		$aPicture = explode(',', $sPicture);
		$grouponEntity = new GrouponEntity();
		$aPictureReturn = array();
		foreach($aPicture as $item){
			$aPictureReturn[] = $grouponEntity->getImage($item);	
		}
		return  $aPictureReturn;
	}
	public function getCommentDefault($deal_id){
		$commentDataService = new DealCommentDataService();
		$listComment = $commentDataService->getItems(array('deal_id' => $deal_id, 'default' => 1));
		$commentEntity = $listComment[0];
		return $commentEntity->comment_text;
	}
	public function olderDealsAction(){
				//can get all deals.....
	
		$city = $this->getQuery ( 'city', 1 );
		$arr = array('G.city_id' => $city);
		$where = " AND ( D.status > 2";
		$where .= " OR DATE_FORMAT(D.expired_deal, '%Y-%m-%d %H:%i:%s') < '".date('Y-m-d') . ' ' . date('H:i:s')."'";
		$where .= " OR D.bought_count >= D.max_bought )";
		
		$search = $this->getPost('search', '');
		if($search != '')
		$where .= " AND G.title LIKE '%". $search ."%'";
		$listDeals = $this->dealsDataService->getAllDeals ( $arr , 'rand()', null, null, $where );
		$this->smarty->assign ( 'listDeals', $listDeals );
		
		$this->smarty->assign('this', $this);
		$this->smarty->assign('grouponEntity', new GrouponEntity());
		
		$this->smarty->assign('pageName', 'olderdeals');
		$this->smarty->assign ( 'SMARTY_CONTENT_PATH', 'Browse/Deals/olderdeals.tpl' );
		$this->smarty->display ( APPLICATION_PATH . '/Layouts/Browse/MainLayoutOlderDeals.tpl' );
	}
}
